<template>
  <div class="history-container">
    <div class="header">
      <h2>历史游戏记录</h2>
      <div class="actions">
        <el-button type="danger" @click="confirmClear" :disabled="records.length === 0">清空记录</el-button>
      </div>
    </div>

    <el-empty v-if="records.length === 0" description="暂无历史记录" />

    <div v-else class="records">
      <div v-for="item in records" :key="item.id" class="record-card">
        <div class="record-header">
          <div class="title">{{ item.roomName || ('房间 ' + item.roomId) }}</div>
          <div class="meta">
            <span>{{ formatDate(item.endedAt) }}</span>
            <span>时长 {{ formatDuration(item.durationSeconds) }}</span>
          </div>
        </div>

        <div class="winner" v-if="item.winner">
          <span class="label">获胜者：</span>
          <span class="name" :style="{ color: item.winner.color }">{{ item.winner.nickname }}</span>
        </div>

        <div class="players">
          <div class="player" v-for="p in item.players" :key="p.id">
            <span class="rank">#{{ p.rank ?? '-' }}</span>
            <span class="color" :style="{ backgroundColor: p.color }"></span>
            <span class="nickname">{{ p.nickname }}</span>
            <span class="area">{{ Number(p.area || 0) }} 像素</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getHistory as getLocalHistory, clearHistory } from '@/utils/gameHistory'
import { fetchHistory, fetchHistoryById } from '@/services/historyService'

const records = ref([])
const loading = ref(false)

onMounted(async () => {
  loading.value = true
  try {
    const remote = await fetchHistory()
    if (Array.isArray(remote) && remote.length > 0) {
      // 去重处理：根据ID去重
      const uniqueRemote = remote.filter((item, index, self) => 
        index === self.findIndex(t => t.id === item.id)
      );
      
      // 初步映射基础信息
      const base = uniqueRemote.map(x => ({
        id: x.id,
        roomId: x.roomCode,
        roomName: x.roomName,
        endedAt: x.endedAt,
        durationSeconds: x.durationSeconds,
        winner: x.winnerPlayerId ? { id: x.winnerPlayerId, nickname: x.winnerNickname, color: x.winnerColor } : null,
        players: []
      }))

      // 并发拉取每条记录的详细玩家信息
      const detailed = await Promise.all(base.map(async (b) => {
        try {
          const d = await fetchHistoryById(b.id)
          const players = Array.isArray(d?.players) ? d.players.map(p => ({
            id: p.playerId ?? p.PlayerId,
            nickname: p.nickname ?? p.Nickname,
            color: p.color ?? p.Color,
            area: Number(p.area ?? p.Area ?? 0),
            rank: Number(p.rank ?? p.Rank ?? 0)
          })) : []
          // 按排名排序（升序）
          players.sort((a, b2) => (a.rank || 0) - (b2.rank || 0))
          return { ...b, players }
        } catch {
          return b
        }
      }))

      records.value = detailed
    } else {
      records.value = getLocalHistory()
    }
  } catch (e) {
    console.error('Failed to fetch history:', e)
    records.value = getLocalHistory()
  } finally {
    loading.value = false
  }
})

function formatDate(ts) {
  try {
    const d = new Date(Number(ts) || Date.now())
    const yyyy = d.getFullYear()
    const mm = String(d.getMonth() + 1).padStart(2, '0')
    const dd = String(d.getDate()).padStart(2, '0')
    const hh = String(d.getHours()).padStart(2, '0')
    const mi = String(d.getMinutes()).padStart(2, '0')
    return `${yyyy}-${mm}-${dd} ${hh}:${mi}`
  } catch {
    return ''
  }
}

function formatDuration(sec) {
  const s = Number(sec) || 0
  const m = Math.floor(s / 60)
  const r = s % 60
  return `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}`
}

function getArea(item, playerId) {
  // 已改为在模板直接使用 p.area，此函数保留兼容旧数据
  const found = Array.isArray(item.players) ? item.players.find(p => p.id === playerId) : null
  return Number(found?.area || 0)
}

function confirmClear() {
  ElMessageBox.confirm('确定清空所有历史记录？', '清空确认', {
    confirmButtonText: '清空',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    clearHistory()
    records.value = []
    ElMessage.success('已清空')
  }).catch(() => {})
}
</script>

<style scoped>
.history-container {
  max-width: 960px;
  margin: 0 auto;
  padding: 24px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.records {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}
.record-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  padding: 16px;
}
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 12px;
}
.record-header .title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.record-header .meta {
  color: #888;
  font-size: 12px;
  display: flex;
  gap: 12px;
}
.winner {
  margin-bottom: 10px;
}
.winner .label {
  color: #666;
}
.winner .name {
  font-weight: 600;
}
.players {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 8px 16px;
}
.player {
  display: flex;
  align-items: center;
  gap: 8px;
}
.player .rank {
  width: 28px;
  text-align: right;
  color: #999;
  font-size: 12px;
}
.player .color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.player .nickname {
  color: #333;
  font-weight: 500;
}
.player .area {
  color: #666;
  margin-left: auto;
  font-size: 12px;
}
</style>


